const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs-extra');

// 配置参数
const config = {
    entry: './service/service.ts',
    outputDir: './dist-service',
    minify: true,
    sourceMap: false
};

// 构建命令
const buildCommand = [
    'ncc',
    'build',
    config.entry,
    '--out', config.outputDir,
    config.minify ? '--minify' : '',
    config.sourceMap ? '--source-map' : ''
].filter(Boolean).join(' ');

console.log(`执行构建命令: ${buildCommand}`);

try {
    // 清理输出目录
    console.log(`清理输出目录: ${config.outputDir}`);
    if (fs.existsSync(config.outputDir)) {
        fs.emptyDirSync(config.outputDir);
    }

    execSync(buildCommand, { stdio: 'inherit' });

    // 复制指定的node_modules到dist目录
    const copyModules = [
        'node_modules/aws-ssl-profiles',
        'node_modules/denque',
        'node_modules/generate-function',
        'node_modules/iconv-lite',
        'node_modules/is-property',
        'node_modules/long',
        'node_modules/lru-cache',
        'node_modules/lru.min',
        'node_modules/mysql2',
        'node_modules/named-placeholders',
        'node_modules/safer-buffer',
        'node_modules/seq-queue',
        'node_modules/sqlstring'
    ];

    // 复制node_modules
    //   copyModules.forEach(modulePath => {
    //     const destPath = path.join(config.outputDir, modulePath);
    //     fs.ensureDirSync(path.dirname(destPath));
    //     fs.copySync(modulePath, destPath);
    //     console.log(`已复制: ${modulePath} -> ${destPath}`);
    //   });

    // 复制public文件夹内容到dist根目录
    if (fs.existsSync('public')) {
        const publicFiles = fs.readdirSync('public');
        publicFiles.forEach(file => {
            const srcPath = path.join('public', file);
            const destPath = path.join(config.outputDir, file);
            fs.copySync(srcPath, destPath);
            console.log(`已复制: ${srcPath} -> ${destPath}`);
        });
    }

    console.log('构建成功');
} catch (error) {
    console.error('构建失败:', error);
    process.exit(1);
}